from django.http import HttpResponse
from ...models.api_keys import ApiKeys
from django.core.serializers import serialize
from ...utils.time_conversion import iso_to_times

import json


def api_keys_list(request):
    '''
    参数：status=true&type=chat
    '''
    api_key_status_str = request.GET.get('status', None)
    api_key_type = request.GET.get('type', None)

    if api_key_status_str is not None and api_key_type is not None:
        api_key_status_bool = api_key_status_str.lower() == 'true'
        all_apikeys = ApiKeys.objects.filter(enabled=api_key_status_bool,type=api_key_type)
    else:
        all_apikeys = ApiKeys.objects.all()

    json_data_str = serialize('json', all_apikeys)
    json_data = json.loads(json_data_str)
    data = []
    for i in range(len(json_data)):
        json_data[i]['fields']['id'] = json_data[i]['pk']

        # 数据处理
        created_at_second = iso_to_times(json_data[i]['fields']['created_at'])
        updated_at_second = iso_to_times(json_data[i]['fields']['updated_at'])
        last_used_at_second = iso_to_times(json_data[i]['fields']['last_used_at'])

        json_data[i]['fields']['created_at'] = created_at_second
        json_data[i]['fields']['updated_at'] = updated_at_second
        json_data[i]['fields']['last_used_at'] = last_used_at_second

        data.append(json_data[i]['fields'])

    res_mes = {
        "code": 0,
        "data": data
    }
    res_mes_json = json.dumps(res_mes, ensure_ascii=False)
    return HttpResponse(res_mes_json)


def api_keys_save(request):
    '''
    保存apikeys
    post
    body add = {
        "enabled": true,
        "platform": "QWen",
        "api_url": "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation",
        "name": "test2",
        "type": "chat",
        "value": "test2"
    }
    body save = {
        "id": 4,
        "created_at": 1719468284,
        "updated_at": 0,
        "platform": "QWen",
        "name": "test2",
        "type": "chat",
        "value": "test2",
        "api_url": "",
        "enabled": true,
        "proxy_url": "",
        "last_used_at": ""
    }
    ########################################################
    ########## add 
    res = {
        "code": 0,
        "data": {
            "id": 4,
            "created_at": 1719468284,
            "updated_at": 0,
            "platform": "QWen",
            "name": "test2",
            "type": "chat",
            "value": "test2",
            "api_url": "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation",
            "enabled": true,
            "proxy_url": "",
            "last_used_at": 0
        }
    }
    ############ save
    res = {
        "code": 0,
        "data": {
            "id": 4,
            "created_at": 1719468285,
            "updated_at": 0,
            "platform": "QWen",
            "name": "test2",
            "type": "chat",
            "value": "test2",
            "api_url": "",
            "enabled": true,
            "proxy_url": "",
            "last_used_at": 0
        }
    }
    '''
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        # 删除没必要的数据
        try:
            del json_obj['created_at']
            del json_obj['updated_at']
            del json_obj['last_used_at']
        except:
            pass

        if "id" in json_obj:
            apikey_instance_list = ApiKeys.objects.filter(id=json_obj['id'])
            if apikey_instance_list:
                apikey_instance = apikey_instance_list[0]
            else:
                res_mes = {
                    "code": 1,
                    "message": "没有这个数据"
                }
                res_mes_json = json.dumps(res_mes, ensure_ascii=False)
                return HttpResponse(res_mes_json)
        else:
            apikey_instance = ApiKeys()

        for key, value in json_obj.items():
            code_str = "apikey_instance.%s = '%s'" % (key, value)
            exec(code_str)
        
        try:
            apikey_instance.save()
        except Exception as e:
            res_mes = {
                "code": 1,
                "message": e
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)
        
        ok_apikey_instance = ApiKeys.objects.get(name=json_obj['name'])
        
        data_str = serialize('json', [ok_apikey_instance])
        data = json.loads(data_str)
        apikeys_str = data[0]["fields"]

        # 数据处理一下
        # str_status =  str(apikeys_str['enabled']).lower()
        # apikeys_str['enabled'] = str_status
        apikeys_str['id'] = data[0]['pk']

        created_at_second = iso_to_times(apikeys_str['created_at'])
        updated_at_second = iso_to_times(apikeys_str['updated_at'])
        last_used_at_second = iso_to_times(apikeys_str['last_used_at'])

        apikeys_str['created_at'] = created_at_second
        apikeys_str['updated_at'] = updated_at_second
        apikeys_str['last_used_at'] = last_used_at_second

        res_mes = {
            "code": 0,
            "data": apikeys_str
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)


def api_keys_set(request):
    '''
    修改apikey状态
    post
    body = {
        "id": 12,
        "filed": "enabled",
        "value": false
    }
    res = {
        "code": 0
    }
    '''
    if request.method == 'POST':
        json_b = request.body
        json_str = json_b.decode('utf-8')
        json_obj = json.loads(json_str)

        try:
            ApiKeys.objects.filter(id=json_obj['id']).update(enabled=json_obj['value'])
        except Exception as e:
            res_mes = {
                "code": 1,
                "message": e
            }
            res_mes_json = json.dumps(res_mes, ensure_ascii=False)
            return HttpResponse(res_mes_json)

        res_mes = {
            "code": 0
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)


def api_keys_remove(request):
    re_id = request.GET.get('id')
    try:
        del_obj = ApiKeys.objects.get(id=re_id)
        del_obj.delete()

        res_mes = {
            "code": 0
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)
    except Exception as e:
        res_mes = {
            "code": 1,
            "message": e
        }
        res_mes_json = json.dumps(res_mes, ensure_ascii=False)
        return HttpResponse(res_mes_json)

